package stone926.mods.more_enchantments.mixins;

import net.minecraft.block.*;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;

import java.util.Random;

@Mixin(FlowerBlock.class)
public class FlowerBlockMixin extends PlantBlock implements Fertilizable {

  protected FlowerBlockMixin(Settings settings) {
    super(settings);
  }

  @Override
  public boolean isFertilizable(BlockView world, BlockPos pos, BlockState state, boolean isClient) {
    return true;
  }

  @Override
  public boolean canGrow(World world, Random random, BlockPos pos, BlockState state) {
    return true;
  }

  @Override
  public void grow(ServerWorld world, Random random, BlockPos pos, BlockState thisState) {
    if (thisState.isOf(Blocks.WITHER_ROSE)) return;

    Iterable<BlockPos> iterateBlockPos = BlockPos.iterate(
      pos.add(2 + random.nextInt(2), 2, 2 + random.nextInt(2)),
      pos.add(-2 - random.nextInt(2), -2, -2 - random.nextInt(2))
    );

    FlowerBlock selfBlock = (FlowerBlock) (Object) this;

    for (BlockPos flowerPos : iterateBlockPos) {
      BlockState targetState = world.getBlockState(flowerPos);
      if ((targetState.isOf(Blocks.AIR)
        || targetState.isOf(Blocks.CAVE_AIR)
        || targetState.isOf(Blocks.VOID_AIR)
        || targetState.isOf(Blocks.GRASS)
        || targetState.isOf(Blocks.TALL_GRASS)

        || (targetState.isOf(MoreEnchantmentsMod.BLACK_MANDALA)
        && thisState.isOf(MoreEnchantmentsMod.CHRYSANTHEMUM)
        && random.nextInt(4) == 0)

      ) && selfBlock.canPlaceAt(selfBlock.getDefaultState(), world, flowerPos)
        && random.nextDouble() < 0.15
      ) {
        world.setBlockState(flowerPos, selfBlock.getDefaultState());
      }
    }

  }

}
